package cn.whx.hrm.webconfig;

import cn.whx.hrm.handler.MyAuthenticationFailureHandle;
import cn.whx.hrm.handler.MyAuthenticationSuccessHandler;
import cn.whx.hrm.handler.MyAuthorDeniedHandler;
import cn.whx.hrm.service.MyUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;
import java.util.ArrayList;
@Configuration //交给spring容器管理
@EnableWebSecurity //开启web安全配置
@EnableGlobalMethodSecurity(prePostEnabled = true) //允许pre 和post的方法注解授权
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private MyUserDetails userDetails;
    public PersistentTokenRepository repository(){
        //创建一个数据库
        JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
        //配置连接池
        repository.setDataSource(dataSource);
        //可以在第一次访问的时候自动创建数据表，用完后注释掉
        repository.setCreateTableOnStartup(true);
        return repository;
    }

    //密码加密器
    @Bean
    public PasswordEncoder getPwdEncoder(){
        /*  return NoOpPasswordEncoder.getInstance();*/
        //使用bcty加密
        return new BCryptPasswordEncoder();
    }
    /* @Bean
      protected UserDetailsService userDetailsService() {
        *//*  InMemoryUserDetailsManager detailsManager = new InMemoryUserDetailsManager();
        //在内存中创建一个用户  真实的应该从数据库中查询
        User user = new User("xin", "1", new ArrayList<>());
        detailsManager.createUser(user);*//*
        return detailsManager;
    }*/
    //http的安全配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().accessDeniedHandler(new MyAuthorDeniedHandler())                  //授权配置
                .and().authorizeRequests()
                .antMatchers("/login").permitAll()  //登录路径放行
                .antMatchers("/login.html").permitAll()//自定义登录页面放行
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().formLogin()                              //允许表单登录
                //.successForwardUrl("/success")             // 设置登陆成功页
                .successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
                .failureHandler(new MyAuthenticationFailureHandle())//认证失败的处理
                .loginPage("/login.html")//指定使用自定义登录界面  不再使用默认的
                .loginProcessingUrl("/login")
                .and().logout().permitAll()                    //登出路径放行 /logout
                .and().csrf().disable();                        //关闭跨站伪造检查

        //记住我的配置
        http.rememberMe().tokenRepository(repository())
                .tokenValiditySeconds(1000)
                .userDetailsService(userDetails);
    }
}
